/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * CaseMemberServiceImpl.java
 */
package com.yixun.qfbao.xf.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.dao.OtherCompanyDao;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.xf.mapper.CaseMemberMapper;
import com.yixun.qfbao.xf.mapper.PremisesMapper;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.PartnerStatusEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * [文件名称]<br>
 * CaseMemberServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 案场人员与驻守楼盘关系表 service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2015-11-10 14:57:23 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("caseMemberService")
public class CaseMemberServiceImpl implements CaseMemberService {

    private static final Logger logger = LoggerFactory.getLogger(CaseMemberServiceImpl.class);
	
	@Autowired
	private CaseMemberMapper mapper;
	@Autowired
	private PremisesMapper premisesMapper;
	@Autowired
	private OtherCompanyDao otherCompanyDao;
	@Autowired
    private PartnerInfoService partnerInfoService;
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<CaseMember> getPageModel(CaseMemberDto entity,int begin,int end){
		Integer total = mapper.count(entity);
		List<CaseMember> rows = mapper.list(entity,begin,end);
	    Page<CaseMember> msr = new Page<CaseMember>(total, rows);
		return msr;
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<CaseMember> selectListByDto(CaseMemberDto entity){
		return mapper.selectListByDto(entity);
	}
	
	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public CaseMember selectByDto(CaseMemberDto entity){
		return mapper.selectByDto(entity);
	}
	
	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	public CaseMember selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	public CaseMemberDto create(CaseMemberDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		mapper.add(entity);
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	public int update(CaseMemberDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}
    
	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int destroy(CaseMemberDto entity) {
		return mapper.del(entity);
	}
	
	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	public int saveOrUpdate(CaseMemberDto entity) {
		if(entity!=null&&entity.getId()!=null){
			return update(entity);
		}else{
			create(entity);
			return 1;
		}
	}
	
	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public CaseMember selectBy(CaseMember entity) {
		if(entity!=null&&entity.getId()!=null){
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	/**
	 * @param premisesName 楼盘名称模糊查询
	 * @return CaseMember列表
	 */
	@Override
	public List<CaseMember> selectListByPremisesName(String premisesName) {
		return mapper.selectListByPremisesName(premisesName);
	}
	
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<CaseMemberDto> selectParAndPreListByDto(CaseMemberDto entity){
		return mapper.selectParAndPreListByDto(entity);
	}
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<CaseMemberDto> selectCaseMemberInfoByPremisesIds(CaseMemberDto entity){
		return mapper.selectCaseMemberInfoByPremisesIds(entity);
	}

	@Override
	public List<CaseMemberDto> selectCMListGroupByPremises(CaseMemberDto entity) {
		return mapper.selectCMListGroupByPremises(entity);
	}

	@Override
	public List<Map<String, Object>> findCompanyList(Long premisesId, List<Long> premisesIds) {
		return mapper.findCompanyList(premisesId, premisesIds);
	}
	
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<CaseMemberDto> selectPremisesListByDto(CaseMemberDto entity){
		return mapper.selectPremisesListByDto(entity);
	}
	
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<CaseMemberDto> getPremisesCMList(CaseMemberDto entity){
		return mapper.getPremisesCMList(entity);
	}

	/**
	 * 驻场人员短信配置
	 * @param list
	 * @return
	 */
	public List<CaseMemberDto> getPremisesCMsmsList(List<Long> list,Long companyId){
		return mapper.selectPremisesCMSmsList(list,companyId);
	}

	/**
	 * @param entity 更新楼盘下的所有联系人
	 * @return 更新行数
	 */
	public int updateForPhoneStatus(CaseMemberDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.editForPhoneStatus(entity);
	}

    @Override
    public List<CaseMemberDto> getDistincPremisesCMList(List<Long> premisesIds, Long companyId) {
        return mapper.getDistincPremisesCMList(premisesIds,companyId);
    }

    /**
     * 获取接收微信模板消息驻场人员微信openid接口
     * @param caseMemberDto
     * @return
     */
    public List<PartnerInfo> selectListForWxMsg(CaseMemberDto caseMemberDto) {
        caseMemberDto.setWxMsgStatus("1");
        List<CaseMemberDto> caseMemberDtoList = mapper.selectListForWxMsg(caseMemberDto);
        if (caseMemberDtoList == null || caseMemberDtoList.size() == 0) {
            logger.info("selectListForWxMsg ---- 获取驻场人员列表失败或者数据为空！");
            return null;
        }
        List<Long> piIdList = caseMemberDtoList.stream().map(CaseMemberDto::getPartnerId).collect(Collectors.toList());
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setIds(piIdList);
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        return partnerInfoService.selectListByDto(partnerInfoDto);
    }

	/**
	 * 复用短信设置
	 * @param companyId
	 */
    public void reuseSmsSetting(Long companyId){
		mapper.reuseSmsSetting(companyId);
	}

	public List<CaseMemberDto> selectListForDept(CaseMemberDto caseMemberDto){
    	return mapper.selectListForDept(caseMemberDto);
	}
	
	/**
	 * 	根据ID 批量修改对应的员工微信消息订阅
	 * @param caseMemberDtos
	 * @return
	 */
	@Override
	public int batchUpdateCaseMemberWxStatus(List<CaseMemberDto> caseMemberDtos) {
		return mapper.batchUpdateCaseMemberWxStatus(caseMemberDtos);
	}
	
	/**
	 * 批量修改员工驻守楼盘信息
	 * @param caseMemberDto
	 * @return
	 */
	@Override
	@Transactional
	public void batchUpdateCaseMemberPremises(CaseMemberDto caseMemberDto, List<Long> premisesIds) {
		//查询当前用户已驻守的楼盘
		caseMemberDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CaseMemberDto> casMemerberList = mapper.selectList(caseMemberDto);
		Map<Long, List<Long>> existUserAndPremisesRels = new HashMap<>();
		// 组装已经驻守的数据
		for (CaseMemberDto caseMemberDto2 : casMemerberList) {
			Long partnerId = caseMemberDto2.getPartnerId();
			Long premisesId = caseMemberDto2.getPremisesId();
			List<Long> existPremisesIds = existUserAndPremisesRels.get(partnerId);
			if(existUserAndPremisesRels.get(partnerId) == null) {
				existPremisesIds = new ArrayList<>();
				existPremisesIds.add(premisesId);
				existUserAndPremisesRels.put(partnerId, existPremisesIds);
			}else {
				existPremisesIds.add(premisesId);
			}
		}
		
		// 根据楼盘ID获取楼盘名称
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setPremisesIds(premisesIds);
		List<Premises> premisesList = premisesMapper.selectListByDto(premisesDto);
				
		List<Long> userIds = caseMemberDto.getUserIds();
		for (Long userId : userIds) {
			List<Long> existPremisesIds = existUserAndPremisesRels.get(userId);
			
			if(CollectionUtils.isEmpty(existPremisesIds)) {
				caseMemberDto.addUserAndPremisesRel(userId, premisesList);
				continue;
			}
			for (Long premisesId: premisesIds) {
				if(!existPremisesIds.contains(premisesId)) {
					for (Premises premises : premisesList) {
						if(premises.getId().longValue() == premisesId.longValue()) {
							caseMemberDto.addUserAndPremisesRel(userId, premises);
							break;
						}
					}
				}
			}
		}

		//设置到案场中
		if(!CollectionUtils.isEmpty(caseMemberDto.getUserAndPremisesRels())) {
			mapper.batchInsert(caseMemberDto);
		}
	}

	@Override
	public void batchDeleted(List<CaseMemberDto> list) {
		mapper.batchDeleted(list);
	}

	@Override
	public void batchAdd(List<CaseMemberDto> list) {
		mapper.batchAdd(list);
	}
}
